/**
 * @author: 子龙
 */
package com.fzl.lotterysystem.common.utils;

import io.lettuce.core.ScriptOutputType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.concurrent.TimeUnit;


@Slf4j
@Configuration
public class RedisUtil {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 设置值
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key, String value) {
        try {
            stringRedisTemplate.opsForValue().set(key, value);
            return true;
        }catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }

    }

    /**
     * 设置过期时间
     * @param key
     * @param value
     * @param time 秒为单位
     * @return
     */
    public boolean set(String key, String value, Long time) {
        try {
            stringRedisTemplate.opsForValue().set(key, value,time, TimeUnit.SECONDS);
            return true;
        }catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * 获取值
     * @param key
     * @return
     */
    public String get(String key) {
        try {
            return StringUtils.hasText(key) ? stringRedisTemplate.opsForValue().get(key) : null;
        }catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }

    }

    /**
     * 删除
     * @param key
     * @return
     */
    public boolean del(String... key) {
        try {
            if (key != null && key.length > 0) {
                if (key.length == 1) {
                    stringRedisTemplate.delete(key[0]);
                }else {
                    stringRedisTemplate.delete(
                            (Collection<String>) CollectionUtils.arrayToList(key)
                    );
                }

            }
            return true;
        }catch (Exception e){
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * 判断key是否存在
     * @param key
     * @return
     */
    public boolean hasKey(String key) {
        try {
            if (StringUtils.hasText(key)) {
                return stringRedisTemplate.hasKey(key);
            }
            return false;
        }catch(Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }
}